// ***************************************************************************
// Caution: modifying this file will affect the integrity of the application.
// ***************************************************************************
// Copyright © 1995-2007, Camstar Systems, Inc. All Rights Reserved.
// This file is the main file that should be included in all forms related to Export-Import functionality.

var checkedInstancesCount = 0;
var oldDropdownSelectHandler = null;
var limitValue = -1;
var oldTreeView_PopulateNodeDoCallBack;
var oldTreeView_ProcessNodeData;
var mTreeView_SavedHtml;
var mWaitingPromptHtml = "";
var functionUpdateCheckedInstancesCount = null;

// Replace old callback handlers with new handlers
function ReplaceCallBackMethods(id, prompt)
{
    oldTreeView_PopulateNodeDoCallBack = TreeView_PopulateNodeDoCallBack;
    oldTreeView_ProcessNodeData = TreeView_ProcessNodeData;
    mTreeView_SavedHtml = "";
    mWaitingPromptHtml = prompt;
    
    if(typeof(ExportLimitArray) != 'undefined')
    {
        limitValue = parseInt(ExportLimitArray[0]);
        CalculateCheckedNodes(id);
    }
    else
    {
        limitValue = -1;
    }   

    // The handler is called while sending request to populate node.
    TreeView_PopulateNodeDoCallBack = 
         function PopulateNodeDoCallBack(context, param)
         {
            oldTreeView_PopulateNodeDoCallBack(context, param);
            // Add waiting.... notice.
            var tdOfText = context.node.parentElement.nextSibling.nextSibling;
            var textEls = tdOfText.getElementsByTagName("A")
            if (textEls.length>0)
            {
                mTreeView_SavedHtml = textEls[0].innerHTML;
                textEls[0].innerHTML = prompt;
            }
         }
    // The handler is called while parsing callback response to populate node.
    TreeView_ProcessNodeData = 
        function ProcessNodeData(result, context)
        {
            oldTreeView_ProcessNodeData(result, context);
            // Restore text on waiting.... notice.
            var tdOfText = context.node.parentElement.nextSibling.nextSibling;
            var textEls = tdOfText.getElementsByTagName("A")
            if (textEls.length>0)
            {
                textEls[0].innerHTML = mTreeView_SavedHtml;
                mTreeView_SavedHtml = "";
            }
            
            if (limitValue!=-1)
            {    
                // process new checked nodes came from response.
                var node = GetNode(context.node); 
                if (node)
                {
                    var nodes = GetChildNodes(node);
                    if (nodes && nodes.length>0)
                    {
                        var inputs = nodes[0].parentElement.getElementsByTagName("INPUT");
                        if(inputs.length > 0)
                        {
                            var prevCheckedInstancesCount = checkedInstancesCount;
                            for(var i = 0; i < inputs.length; i++)
                            {
                                if(inputs[i].type == "checkbox" && inputs[i].checked == true)
                                    checkedInstancesCount ++;
                            }
                            
                            if(checkedInstancesCount > prevCheckedInstancesCount && checkedInstancesCount > limitValue)
                            {
                                // Display ExportLimitLabel
                                var label = document.getElementById(ExportLimitArray[2]);
                                if(label != null)
                                    alert(label.innerText);
                            }
                        }
                    }
                }
             }
        }
} // ReplaceCallBackMethods

// Increases or decreases value of checkedInstancesCount.
// If the limit has been exceeded returns 'false', otherwise 'true'.
function UpdateCheckedInstancesCount(isChecked)
{
    checkedInstancesCount += (isChecked) ? 1 : -1;
    if(checkedInstancesCount < 0)
    {
        checkedInstancesCount = 0;
    }
    else if(isChecked)
    {
        if(checkedInstancesCount > limitValue)
        {
            checkedInstancesCount --;            
            
            // Display ExportLimitLabel
            var label = document.getElementById(ExportLimitArray[2]);
            if(label != null)
                alert(label.innerText);

            return false;
        }
    }   
    return true;
} // UpdateCheckedInstancesCount

// Gets node's Table element
//    element - any element inside table
function GetNode(element)
{
    var tbl = element;
    while( tbl && tbl.tagName != "TABLE")
    {
        tbl = tbl.parentElement;
    }
    return tbl;
} // GetNode

// Gets root div node of tree control 
function GetRootDiv(element)
{
    var tbl = element.parentElement;
    var div = null;
    while(tbl)
    {
        if (tbl.tagName == "TABLE" && tbl.getAttribute("rootId"))
        {
            div = tbl.parentElement;
            break;
        }
        tbl = tbl.parentElement;
    }
    return div;
} //GetRootDiv

// Gets child nodes of the current node.
function GetChildNodes(nodeTable)
{
    // Get node id
    var nodeId = null;
    var row = nodeTable.rows[0];
    var cellWithText = row.cells[row.cells.length-1];
    if (cellWithText && cellWithText.lastChild)
    {
        var re = new RegExp("t(\\d+)$");
        var x = re.exec(cellWithText.lastChild.id);
        if (RegExp.$1)
            nodeId = cellWithText.lastChild.id.substr(0, x.index) + "n" + RegExp.$1;
    }

        
    var childrenDiv = document.all[nodeId+"Nodes"];
    if (childrenDiv)
        return childrenDiv.children;
    else
        return null;    
} // GetChildNodes

// Executes func for all nodes of type targetNode
function ExecForNodes(nodes, targetNode, func, p1)
{
    var child;
    for(var i=0; i<nodes.length; i++)
    {   
        child = nodes[i];
        if( child.tagName == "TABLE")
        {
            var itemType = GetItemType(child)
            if (itemType && targetNode.indexOf(itemType)!=-1)
            {
                if (func)
                    if (! func(child, itemType, p1))
                        break;
            }
        }
    }
} //ExecForNodes

// Sets checked/unchecked status for the node
function SetChecked(node, itemType, isChecked)
{
    var checkBoxElement = null;
    
    if (itemType == "NDO" || itemType == "RDORev")
    {
        if (node.tagName == "TABLE")
        {
            var row = node.rows[0];
            checkBoxElement = row.cells[row.cells.length-1].firstChild;
        }
        if (checkBoxElement && checkBoxElement.tagName=="INPUT" && checkBoxElement.type=="checkbox")
        {
            checkBoxElement.checked = isChecked;
            if (limitValue!=-1)
                return functionUpdateCheckedInstancesCount(isChecked);
            else
                return true;
        }
        return false;
    }
    else if (itemType == "RDO")
    {
        // Sets checked for revisions
        var childNodes = GetChildNodes(node);
        if(childNodes)
        {
            ExecForNodes(childNodes, "RDORev", SetChecked, isChecked);
        }        
        return true;
    }
    return false;
} // SetChecked

// Gets item's type
function GetItemType(node)
{
    var row = node.rows[0];
    var cellWithText = row.cells[row.cells.length-1];
    if (cellWithText.lastChild.tagName == "A")
        return cellWithText.lastChild.getAttribute("it");
    else
        return null;
} //GetItemType


// The event handler called while any element of the tree is clicked.
function ClickTreeNode(clickedElement)
{
    if (clickedElement.tagName == "INPUT")
    {
        if (clickedElement.type == "checkbox")
        {
            functionUpdateCheckedInstancesCount = UpdateCheckedInstancesCount;
            var isChecked = clickedElement.checked;
            if(limitValue != -1 && !functionUpdateCheckedInstancesCount(isChecked))
            {
                clickedElement.checked = false;
                return;
            }
            
            var node = GetNode(clickedElement);
            if ( GetItemType(node)=="Class" )
            {
                var childNodes = GetChildNodes(node);
                if(childNodes)
                {
                    ExecForNodes(childNodes, "NDO|RDO", SetChecked, isChecked);
                }
            }            
        }
     }
     else if (clickedElement.tagName == "IMG")
     {
        var folderImg = clickedElement.parentElement.parentElement.nextSibling.firstChild.firstChild;
        if (!folderImg || (folderImg && !folderImg.src))
            folderImg = clickedElement;
        if (folderImg && folderImg.src)
        {
            if (folderImg.src.indexOf(mFolderOpenImage)!=-1)
                folderImg.src = mFolderClosedImage;
            else if (folderImg.src.indexOf(mFolderClosedImage)!=-1)
                folderImg.src = mFolderOpenImage;
        }
     }
     else if (clickedElement.tagName == "A")
     {
        var folderImg = clickedElement.parentElement.previousSibling.firstChild.firstChild;                
        if (folderImg && folderImg.src)
        {
            if (folderImg.src.indexOf(mFolderOpenImage)!=-1)
                folderImg.src = mFolderClosedImage;
            else if (folderImg.src.indexOf(mFolderClosedImage)!=-1)
                folderImg.src = mFolderOpenImage;
        }
     }
} // ClickTreeNode           

//Check/Uncheck all nodes in the tree
function OnInstanceTreeSelectAll(treeId, IsSelected)
{
    var tree = document.getElementById(treeId);
    if(tree != null)
    {
        var allChildren = tree.getElementsByTagName("INPUT");
        for(var i=0; i<allChildren.length; i++)
        {
            if(allChildren[i].type == "checkbox")
                allChildren[i].checked = IsSelected;
        }
    }
    return false;
} //OnInstanceTreeSelectAll

// Add loading... text while data is loading on Import form
function WaitingNotifyingScript(controlId)
{
    var selectObj = document.all[controlId]
    oldDropdownSelectHandler = selectObj.onchange;
    selectObj.onchange = 
        function newSelectOnChange()
        {
            var divTree = document.all["InstancesTree"];
            divTree.innerHTML = mWaitingPromptHtml;
            oldDropdownSelectHandler();
        }
} //WaitingNotifyingScript

// Calculates number of all checked nodes.
function CalculateCheckedNodes(treeId)
{
    var tree = document.getElementById(treeId);
    if(tree != null)
    {
        var allChildren = tree.getElementsByTagName("INPUT");
        for(var i=0; i<allChildren.length; i++)
        {
            if(allChildren[i].type == "checkbox")
                if (allChildren[i].checked) checkedInstancesCount++;
        }
    }
} //CalculateCheckedNodes

// Adjust row height to fully display cell content
function ImpExpLogGrid_InitializeLayoutHandler(gridName)
{
    var grid = igtbl_getGridById(gridName);
    if (grid)
    {

        for (var i = 0; i < grid.Rows.length; i++)
        {
            var grpRow = grid.Rows.getRow(i);
            AdjustGridRowsHeights(grpRow.Element);
        }

        if (grid.getActiveRow() != null)
        {
            // Scroll vision to active row
            var tr = grid.getActiveRow().Element;
            // Row top in the grid's div
            if (tr != null)
            // aligns the scrolled element with the top of the scroll area.
                window.setTimeout("document.all['" + tr.id + "'].scrollIntoView(true);", 100);
        }
    }
} //ImpExpLogGrid_InitializeLayoutHandler